package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@RestController
@RequestMapping("/setmeal")
public class Mobile_SetmealController {
    //注入服务
    @Reference
    private SetmealService setmealService;

   @Autowired
    private JedisPool jedisPool;

    /**
     * 查询所有套餐
     * @return
     */
    @PostMapping("/getSetmeal")
    public Result getSetmeal() {
        try {
            Jedis resource = jedisPool.getResource();
            //1. 从redis中获取所有分类信息
            List<Setmeal> setmeal = JSON.parseArray(resource.hget("Setmeal",RedisMessageConstant.SELECT_CHECKGROUP_RESOURCES), Setmeal.class);
            //2.判断jsonStr是否为空
            if (setmeal == null || setmeal.size()==0) {
                //表示redis中没有分类信息
                //3.调用dao层的方法到MySQL数据库获取
                setmeal = setmealService.getSetmeal();
                //将categoryList集合转换成json字符串，然后存放到redis中
                resource.hset("Setmeal",RedisMessageConstant.SELECT_CHECKGROUP_RESOURCES, JSON.toJSON(setmeal).toString());
            }
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    /**
     * 根据套餐ID查询完整套餐详情
     * @param id
     * @return
     */
    @PostMapping("/findById")
    public Result findById(Integer id) {
        try {
                Jedis resource = jedisPool.getResource();
                //1. 从redis中获取所有分类信息
                Setmeal setmeal1 = JSON.parseObject(resource.get(RedisMessageConstant.SELECT_SETMEAL_RESOURCES+id), Setmeal.class);
                //2.判断jsonStr是否为空
                if (setmeal1  == null ) {
                    //表示redis中没有分类信息
                    //3.调用dao层的方法到MySQL数据库获取
                    setmeal1 = setmealService.findById(id);
                    //将categoryList集合转换成json字符串，然后存放到redis中
                    resource.set( RedisMessageConstant.SELECT_SETMEAL_RESOURCES+id,JSON.toJSONString(setmeal1));
                }
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal1);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }
}
